package com.yorick.common.error;

import com.yorick.common.Result.SimpleFactory.ResultFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@RestControllerAdvice
public class YorickExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Map<String, Object> allExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) {
        log.error("system got error: {}",ex);
        if(ex instanceof MethodArgumentNotValidException){
            return ResultFactory.failure("0","传入参数错误",null).display();
        }
        return ResultFactory.failure("0","系统错误",null).display();
    }
    @ExceptionHandler(value = YorickException.class)
    public Map<String, Object> yorickExceptionHandler(HttpServletRequest request, HttpServletResponse response, YorickException ex) {
        log.error("yorick exception throw error: {}",ex.getMessage());
        return ResultFactory.failure(ex.getFlag(),ex.getMessage(),null).display();
    }
}
